import React, { memo, useEffect, useState } from 'react';
import { message, Spin, Button, Checkbox } from 'antd';
import classnames from 'classnames';

import { BottomAction } from '@/components';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { isSuccess } from '@/utils/request';
import pageTabUtil from '@/utils/pageTabUtil';
import { withRoutePage } from '@/utils/enhanceUtils';
import { queryConfig, saveChartData } from '@/services/salaryManage/salaryChart';

import tabMessageUtil from '@/pages/SalaryManage/utils/tabMessageUtil';
import EditChartWrapper from './component/EditChartWrapper';
import useAlreadyChoose from './hooks/useAlreadyChoose';
import useTab from './hooks/useTab';

import styles from './style.less'

const PerspectivePic = memo(({ location }) => {
    const { query } = location
    const { organizationCode } = query
    const [configList, setConfigList] = useState([])
    const [tabsVal, setTabsVal] = useState('addSummary')
    const [loading, setLoading] = useState(false)

    useEffect(() => {
        const initFn = async () => {
            setLoading(true)
            const configParam = await queryConfig({ organizationCode, isLoadAllChart: 1 })
            setLoading(false)
            if (isSuccess(configParam)) {
                setConfigList(configParam.data?.specialItemInfoList)
            } else {
                message.error(configParam.msg);
            }
        }
        if (organizationCode) {
            initFn()
        }
    }, [organizationCode])

    // 切换tab
    const changeTab = tabKey => {
        setTabsVal(tabKey)
    }

    // 取消按钮
    const handleCancel = () => {
        pageTabUtil.closeTab();
    };

    // 保存按钮
    const handleSave = async () => {
        setLoading(true)
        const paramList = configList.filter(item => item.isEnable)
        const saveRequest = await saveChartData({
            organizationCode,
            specialItemInfoList: paramList
        })
        setLoading(false)

        if (isSuccess(saveRequest)) {
            message.success(saveRequest.msg)
            tabMessageUtil.noticeFromRefresh();
            handleCancel()
        } else {
            message.error(saveRequest.msg)
        }
    }


    // 选中或者取消
    const handleChange = ({ globalType: type }) => {
        const newList = configList.map(item => {
            const { globalType, isEnable, ...othersParam } = item
            return {
                ...othersParam,
                globalType,
                // eslint-disable-next-line no-nested-ternary
                isEnable: type === globalType ? !isEnable : isEnable
            }
        })
        setConfigList(newList)
    }

    // 取消全部
    const handleChooseAll = () => {
        const newList = configList.map(item => {
            const { isEnable, ...othersParam } = item
            return {
                ...othersParam,
                isEnable: false
            }
        })

        setConfigList(newList)
    }

    const { render: renderChooseWrapper } = useAlreadyChoose(configList, handleChange, handleChooseAll);
    const { render: renderTabs } = useTab(configList, tabsVal, changeTab);

    // 右上方选中框
    const ChooseWrapper = ({ value }) => (<Checkbox checked={value}></Checkbox>)

    // 图表选中样式
    const chooseStyles = isEnable => isEnable ? {
        borderColor: '#FF9E00',
        cursor: 'pointer'
    } : {
        cursor: 'pointer'
    }

    return (
        <PageHeaderWrapper type="success">
            <Spin spinning={loading}>
                <div className={styles.chartWrapper}>
                    <div className={classnames(styles.chartHeader, styles.header)}>
                        <div className={styles.title}>编辑图表</div>
                    </div>
                    {renderChooseWrapper()}
                    {renderTabs()}
                    <div style={{ marginTop: -16 }}>
                        {
                            configList.filter(item => item.parentGlobalType === tabsVal).map(
                                item =>
                                    <EditChartWrapper
                                        key={item.globalType}
                                        title={item.globalName}
                                        style={chooseStyles(item.isEnable)}
                                        onClick={() => handleChange(item)}
                                        organizationCode={organizationCode}
                                        chartConfig={item}
                                        settingWrapper={<ChooseWrapper value={item.isEnable} />} />
                            )
                        }
                    </div>
                </div>

            </Spin>
            <BottomAction>
                <span className={styles.chooseNum}>已选{configList.filter(item => item.isEnable).length}个</span>
                <Button onClick={handleCancel}>
                    取消
                </Button>
                <Button type="primary" onClick={handleSave} loading={loading}>
                    保存
                </Button>
            </BottomAction>
        </PageHeaderWrapper>
    )
})

export default withRoutePage(PerspectivePic)
